// 引入接口文件
import {
  queryAgent,
  create,
  queryInfo,
  importAccount,
  submit,
  delFile,
  projectFilter,
  queryProductList
} from './commissionsDistRulesDetailServ'

// 对象和JSON字符串互转
// import { parse } from 'qs'
// 弹出消息框
import { Modal,message } from 'antd'
const confirm = Modal.confirm;
// 日期处理对象
// import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import $ from 'jquery'
import { isEmpty, isArray, cloneDeep, merge, pick,set,get } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
// import AppBus from '../../../utils/bus'
import { download} from 'utils/util'
import config from 'config/config'
// import {reqInform, showConfirm} from 'utils/notification'
// import { array } from 'prop-types';
// 初始默认状态
const defultState = {
  id: '',
  keys: 0,
  url: '',
  loading: false,
  distCoId: '',
  submitType: '',
  btnLoading: false,
  projectFilterParams: [],
  actionType: 'detail', //查看
  selectedRowKeys: [],
  distributionNameList: [],
  biz:{},
  biz1: {},
  biz2: {},
  biz3: {},
  biz4: {},
  imageUrls: [],
  uploadFileObj: {//导入
    visible: false,
    loading: false,
  },
  fileList: [],
  formatsKey: '',
  detail:{
    name: '',
    projectName:'',
    projectId:'',
    regionName: '',
    computeNodes:'',
    startTime: '',
    endTime:'',
    remark: '',
    noCommission: 0,//特例规则状态
    noCommissionRemark: '',//特例规则说明
    // contractId:  '', //合同id
    // contractAnnex:  '',//合同url
    // enclosureId:  '',//附件ID
    // enclosureUrl:  '',//附件url
    // enclosureName:   '',//附件名称
    enclosureList:[],
    contractList: [],
    commissionRuleDetail:[]
  },
  tableObj: {
    distCoId: '',
    distCoName: '',
    // productId:'',
    productName: '',
    productList: [],
    productSelectedKeys: [],
    productSelectedRows: [],
    commType: '',
    commTypeName: '',
    intertemporal: '',
    numberStart: '',
    numberEnd: '',
    amountStart: '',
    amountEnd: '',
    ratioNum: '',
    amount: '',
    startTime: '',
    endTime: '',
    // contractId:'',
    // enclosureUrl: '',
    // enclosureId: '',
    // enclosureName: '',
    enclosureList:[],
    contractList:[],
    remark: '',
  },
  // 表格数据
  tableData: {
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  
  selectedKeys: [],
  selectedRows: [],
  
  projectModalObj: {
    visible: false,
  },
  formatsModalObj: {
    visible: false,
  },
  codeModalObj: {
    visible: false,
  },
  enclosureNameModalObj: {
    visible: false,
  },
  fileModalObj: {
    visible: false,
  },
  searchData: {
    productName: '',
  },
  productDataList:[],
  productListObj: {
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  productPageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
}
// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          query.id=query.id+''
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          console.log('subscriptions', pathname, query)
          if (query.actionType == 'check' ||query.actionType == 'upVersion' ) {
            // dispatch({type: 'queryInfo',payload: {actionType: query.actionType,id: query.id, } })
          } else {
            dispatch({type: 'updateStore',payload: {actionType: query.actionType,id: query.id, } })
          }
          dispatch({type: 'projectFilter',payload: {actionType: query.actionType,id: query.id, } })
          dispatch({type: 'queryProductList',payload: {} })
        } // end if
      }) // end listen
    },
  },
  
  // 方法列表
  effects: {
    * queryProductList({payload}, {put, call, select}) {
      let {productListObj,productDataList,actionType} = yield select(state => state[tmpModule.namespace])
      let params = {
        pageSize:'10000',
        pageNo:'1',
      }
      let { success, msg, rows } = yield call(queryProductList, {...params})
      if(success){
        productListObj.dataSource = rows
        productDataList = rows
        yield put({type: 'updateStore', payload: {productListObj,productDataList}})
        if(actionType == 'edit'||actionType == 'upVersion'||actionType == 'check'){
          yield put({type: 'queryInfo', payload: {}})
        }
      }
    },
    *queryAgent({payload},{put,select,call}){
      let {detail,distributionNameList} = yield select(state => state[tmpModule.namespace])
      if(!detail.projectId){
        message.warn('请先选择项目名称')
        return false
      }
      let params = {
        projectId: detail.projectId,
        tagType: 0
      }
      const { success, msg, data=[] } = yield call(queryAgent, {...params})
      if(success&&data.length){
        for(var i=0;i<data.length;i++){
          for(var j =data.length - 1; j > 0; j--){
            if(data[i].orgName ==  data[j].orgName && i != j){
              data.splice(j, 1);
            }
          }
        }
        distributionNameList = data
        yield put({
          type: 'updateStore',
          payload: {
            distributionNameList
          }
        })
      }
    },
    *create({payload},{put,select,call}){
      let {submitType,detail,tableData} = yield select(state => state[tmpModule.namespace])
      if(detail.enclosureList&&!detail.enclosureList.length&&detail.contractList&&!detail.contractList.length&&detail.noCommission){
        message.error('特例规则合同编号与关联附件至少选择一个')
        return false
      }
      let params = detail
      let tempList = tableData.dataSource
      let find = false;
      let required = false
      let arr = []
      for (var i = 0; i < tempList.length; i++) {
        if(!tempList[i].enclosureList.length && !tempList[i].contractList.length){
          required = true; break;
        }
          for (var j = i + 1; j < tempList.length; j++) {
              if (tempList[i].distCoName == tempList[j].distCoName 
                && tempList[i].distCoId==tempList[j].distCoId 
                // && tempList[i].productId==tempList[j].productId 
                && tempList[i].productName==tempList[j].productName 
                && tempList[i].commType==tempList[j].commType
                && tempList[i].commTypeName==tempList[j].commTypeName
                && tempList[i].numberStart==tempList[j].numberStart
                && tempList[i].numberEnd==tempList[j].numberEnd
                && tempList[i].amountStart==tempList[j].amountStart
                && tempList[i].amountEnd==tempList[j].amountEnd
                && tempList[i].ratioNum==tempList[j].ratioNum
                && tempList[i].amount==tempList[j].amount
                && tempList[i].startTime==tempList[j].startTime
                && tempList[i].endTime==tempList[j].endTime
                // && tempList[i].contractId==tempList[j].contractId
                // && tempList[i].enclosureName==tempList[j].enclosureName
                // && tempList[i].enclosureUrl==tempList[j].enclosureUrl
                && tempList[i].remark==tempList[j].remark
                ){
                   arr.push(tempList[i])
                   arr.push(tempList[j])
                   find = true; break;
                  }
          }
          if (find) break;
      }
      if(required){
        message.error('合同编号与关联附件至少选择一个')
        return false
      }
      arr = new set(arr)
      for(var item of arr){
        $(`[data-row-key=${item.key}]`).css("border-left","4px solid red")
      }
      if(find){
        message.error('规则明细数据重复，不允许保存')
        return false
      }
      params.commissionRuleDetail = tableData.dataSource
      const { success, msg, id } = yield call(create, {...params})
      if(!params.id){
        //不包含ID为录入
        if(success){
          if(submitType == '提交审批'){
            yield put({type: 'updateStore', payload: {btnLoading: true,}})
            yield put({type: 'submit', payload: {id: id}})
          }else{
            message.success('保存成功')
            hashHistory.push({
              pathname: '/home/commissions/commissionsDistRules',
              query: {}
            })
          }
        }
      }else{
        //包含Id为编辑
        // const { success, msg, id ,data} = yield call(create, {...params})
        if(success){
          if(submitType == '提交审批'){
            yield put({type: 'submit', payload: {id: id}})
          }else{
            message.success('修改成功')
            hashHistory.push({
              pathname: '/home/commissions/commissionsDistRules',
              query: {}
            })
          }
        }
      }
    },
    *queryInfo({payload}, {put, select, call}){
      let {id,detail,tableData,productDataList} = yield select(state => state[tmpModule.namespace])
      let params = { "id":id }
      const { success, msg, data=[] } = yield call(queryInfo, {...params})
      if(success){
        detail = data
        for(var iit of data.listRuleDetailVo){
          iit.productSelectedKeys = []
          iit.productSelectedRows = []
        }
        for(var i=0;i<productDataList.length ;i++){
          for(var itemed of data.listRuleDetailVo){
            if(itemed.productList.length){
              for(var itt of itemed.productList){
                if(productDataList[i].productId == itt.productId){
                  itemed.productSelectedKeys.push(i)
                  itemed.productSelectedRows.push(productDataList[i])
                }
              }
            }
          }
        }
        tableData.dataSource = data.listRuleDetailVo
        yield put({
          type: 'updateStore',
          payload: {
            ...payload,detail,tableData
          }
        })
      }
    },
    * importAccount ({payload}, {put, call, select}) {
      let {detail,uploadFileObj, imageUrls} = yield select(state => state[tmpModule.namespace])
      let fileUrl = imageUrls[0] && imageUrls[0].url || ''
      let fileName = imageUrls[0] && imageUrls[0].name || ''
     
      if (!fileUrl) {
        message.error('请上传文件')
        return false
      }
      uploadFileObj.loading = true
      yield put({type: 'updateStore', payload: {uploadFileObj}})
      let params = {
        url: fileUrl,
        fileName: fileName,
        projectId: detail.projectId
      }
      const {data, success, msg} = yield call(importAccount, {...params})
      if (success === true) {
        message.success('操作成功')
      }
      uploadFileObj.visible = false
      uploadFileObj.loading = false
    },

    *submit({payload},{put,select,call}){
      let params = {
        id: payload.id,
        tab: 1
      }
      const { success, msg, data } = yield call(submit, {...params})
      if(msg){
        yield put({type: 'updateStore', payload: {btnLoading: false,}})
      }
      if(success){
        message.success('提交成功')
        hashHistory.push({
          pathname: '/home/commissions/commissionsDistRules',
          query: {}
        })
      }
    },
    *delFile({payload},{put,select,call}){
      let params = {
        id: payload.fileId,
      }
      const { success, msg, data } = yield call(delFile, {...params})
      if(success){
        message.success('删除成功')
      }
    },
    *projectFilter({payload}, {put, call, select}) {
      let {projectFilterParams} = yield select(state => state[tmpModule.namespace])
     
      const {rows, success} = yield call(projectFilter)
      if(success){
        projectFilterParams = rows
        yield put({
          type: 'updateStore',
          payload: {
            projectFilterParams
          }
        })
      }
    },
    
    * selectedKeysChange ({payload}, {put, select, call}) {
      let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
      selectedRowKeys=payload.selectedRowKeys
      selectedRows=payload.selectedRows
      yield put({
        type: 'updateStore',
        payload: {
          selectedRowKeys,selectedRows
        }
      })
    },
    * selectedKeysChange1 ({payload}, {put, select, call}) {
      let {tableData,formatsKey} = yield select(state => state[tmpModule.namespace])
      for(var item of tableData.dataSource){
        if(item.key == formatsKey){
          item.productSelectedKeys =payload.selectedRowKeys
          item.productSelectedRows =payload.selectedRows
        }
      }
      yield put({
        type: 'updateStore',
        payload: {
          tableData
        }
      })
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
